package org.dbpt.performance;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Item containing other items. E.g. if you need to compose some SQL statements
 * within one test you can use the class.
 * @author Sergey Grigorchuk (sergey.grigorchuk@gmail.com)
 */
public class ContainerItem extends MeasureProviderAdapter implements DBPTItem, ConnectionConsumer {

	private List<DBPTItem> children;
	private String echo;

	public ContainerItem() {		
	}
	
	public ContainerItem(DBPTItem child) {
		this(new ArrayList<DBPTItem>(Arrays.asList(new DBPTItem[]{child})));
	}
	
	public ContainerItem(DBPTItem child1, DBPTItem child2) {
		this(new ArrayList<DBPTItem>(Arrays.asList(new DBPTItem[]{child1, child2})));
	}
	
	public ContainerItem(DBPTItem child1, DBPTItem child2, DBPTItem child3) {
		this(new ArrayList<DBPTItem>(Arrays.asList(new DBPTItem[]{child1, child2, child3})));
	}
	
	public ContainerItem(List<DBPTItem> children) {
		super();
		this.children = children;
	}

	public List<DBPTItem> getChildren() {
		return children;
	}

	public void setChildren(List<DBPTItem> children) {
		this.children = children;
	}

	public String getEcho() {
		return echo;
	}

	public void setEcho(String echo) {
		this.echo = echo;
	}

	@Override
	public void prepare() {
		for(DBPTItem item : children)
			item.prepare();
	}

	@Override
	public void doIteration() {
		if(echo != null) {
			System.out.println(echo);
		}
		for(DBPTItem item : children)
			item.doIteration();
	}

	@Override
	public void cleanup() {
		for(DBPTItem item : children)
			item.cleanup();
	}

	@Override
	public void setConnection(Connection connection) {
		for(DBPTItem item : children) {
			if(item instanceof ConnectionConsumer) {
				ConnectionConsumer connectionConsumer = (ConnectionConsumer) item;
				connectionConsumer.setConnection(connection);
			}
		}
	} 
}
